﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace COFE.Core.Actions
{

    public interface ISchedule
    {
        /// <summary>
        /// Schedule id.
        /// </summary>
        Guid Id { get; }

        

        IWork Work { get; }

        /// <summary>
        /// Work name.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// Library of the work, these are derived from Work.Name.
        /// </summary>
        string WorkLib { get; }

        /// <summary>
        /// Class name of the work, these are derived from Work.Name.
        /// </summary>
        string WorkType { get; }

        /// <summary>
        /// Parameter of the work, these are derived from Work.Name.
        /// </summary>
        string WorkParam { get; }


        int RetryCount { get; set; }

        /// <summary>
        /// Return true if completed Successfully or RetryCount = 0.
        /// WorkScheduler requeue the schedule if IsFinished = false.
        /// </summary>
        bool IsFinished { get; }

        WorkPriority Priority { get; }
        IUserProfile User { get; }

        /// <summary>
        /// _time added to WorkScheduler schedule list.
        /// </summary>
        DateTime ScheduledTimeUtc { get; set; }

        /// <summary>
        /// _time an ant start running the work, fetch from WOrk.StartTimeUtc.
        /// </summary>
        DateTime StartTimeUtc { get; }

        /// <summary>
        /// _time a work finished, fetch from SimpleWork.EndTimeUtc.
        /// </summary>
        DateTime EndTimeUtc { get; }

        /// <summary>
        /// Last error when finished, if there's one, fetch from SimpleWork.Result.
        /// </summary>
        Exception LastError { get; }

        bool CheckCanRetry();
    }

    public static class IScheduledWorkInfoExtension
    {
        public static void SortWork(this List<ISchedule> workInfoList)
        {
            workInfoList.Sort(
                new Comparison<ISchedule>(
                    (first, second) =>
                    {
                        if (first.Priority > second.Priority)
                            return -1; //Higher Priority.
                        else if (first.Priority < second.Priority)
                            return 1;
                        else if (first.ScheduledTimeUtc < second.ScheduledTimeUtc)
                            return -1; //Schedulefirst
                        else return 1;
                    })

                    );
        }
    }
}
